//
//  AddTagViewController.m
//  XiangMuB
//
//  Created by lanou3g on 16/8/16.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "AddTagViewController.h"

#import "TagTextField.h"
#import "UIView+FrameView.h"
#import "TagButton.h"
#import "MBProgressHUD.h"

@interface AddTagViewController ()<UITextFieldDelegate>

@property (strong, nonatomic) NSMutableArray *tagButtons;

@property (strong, nonatomic) UIView *contentView;

@property (strong, nonatomic) TagTextField *textField;

@property (strong, nonatomic) UIButton *addButton;

@end

@implementation AddTagViewController


- (NSMutableArray *)tagButtons{
    
    if (_tagButtons == nil) {
        
        _tagButtons = [NSMutableArray array];
    }
    return _tagButtons;
}

- (UIButton *)addButton{
    
    if (!_addButton) {
        
        UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        addButton.width = self.contentView.width;
        addButton.height = 35;
        
        [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [addButton addTarget:self action:@selector(addButtonClick) forControlEvents:UIControlEventTouchUpInside];
        addButton.titleLabel.font = [UIFont systemFontOfSize:14];
        addButton.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5);
        addButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        
        addButton.backgroundColor = [UIColor colorWithRed:74/255.0 green:139/255.0 blue:209/255.0 alpha:1.0];
        
//        addButton.backgroundColor = [UIColor yellowColor];
        
        [self.contentView addSubview:addButton];
        _addButton = addButton;
        
    }
    return _addButton;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNavigation];
    
    [self setupContentView];
    
    [self setupTextField];
    
    [self setupTags];
    
}


- (void)setupTags{
    
    for (NSString *tag in self.tags) {
        
        self.textField.text = tag;
        [self addButtonClick];
        
    }
}

- (void)setupContentView{
    
    UIView *contentView = [[UIView alloc] init];
    contentView.frame = CGRectMake(5, 64 + 5, self.view.frame.size.width - 2 * 5, [UIScreen mainScreen].bounds.size.height);
    
    [self.view addSubview:contentView];
    
    self.contentView = contentView;
    
}


- (void)setupTextField{
    
    __weak typeof(self) weakself = self;
    
    TagTextField *textField = [[TagTextField alloc] init];
    
    textField.backgroundColor = [UIColor orangeColor];
    
    textField.width = self.contentView.width;
    textField.deleteBlock = ^{
      
        if (weakself.textField.hasText) {
            return ;
        }
        
        [weakself tagButtonClick:[weakself.tagButtons lastObject]];
        
    };
    
    textField.delegate = self;
    
    [textField addTarget:self action:@selector(textDidChangechange) forControlEvents:UIControlEventEditingChanged];
    
    [textField becomeFirstResponder];
    [self.contentView addSubview:textField];
    self.textField = textField;
    
}




- (void)tagButtonClick:(TagButton *)tagButton{
    
    [tagButton removeFromSuperview];
    [self.tagButtons removeObject:tagButton];
    
    [UIView animateWithDuration:0.25 animations:^{
       
        [self updateTagButtonFrame];
        
        [self updateTextFieldFrame];
        
    }];
    
}


- (void)updateTagButtonFrame{
    
    for (int i = 0; i < self.tagButtons.count; i++) {
        
        TagButton *tagButton = self.tagButtons[i];
        
        if (i == 0) {
            
            tagButton.x = 0;
            tagButton.y = 0;
            tagButton.imageView.width = 30;
            
        } else {
            
            TagButton *lastTagButton = self.tagButtons[i - 1];
//            tagButton.width = size.width + 15;
            CGFloat leftWidth = CGRectGetMaxX(lastTagButton.frame) + 5;
            CGFloat rightWidth = self.contentView.width - leftWidth;
            
            if (rightWidth >= tagButton.width) {
                tagButton.y = lastTagButton.y;
                tagButton.x = leftWidth;
            } else {
                tagButton.x = 0;
                tagButton.y = CGRectGetMaxY(lastTagButton.frame) + 5;
            }
            
            
            
        }
        
        
    }
    
}

- (void)updateTextFieldFrame{
    
    TagButton *lastTagButton = [self.tagButtons lastObject];
//    CGFloat leftWidth = CGRectGetMaxX(lastTagButton.frame) + 5;
//    
//    if (self.contentView.width - leftWidth >= [self textFieldTextWidth]) {
//        
//        self.textField.y = lastTagButton.y;
//        self.textField.x = leftWidth;
//        
//    } else {
    
        self.textField.x = 0;
        self.textField.y = CGRectGetMaxY(lastTagButton.frame) + 5;
//    }
    
}

//- (CGFloat)textFieldTextWidth{
//    
//    
//    CGFloat textW = [self.textField.text sizeWithAttributes:@{NSFontAttributeName:self.textField.font}].width;
//    return MAX(100, textW);
//}


#pragma mark eventtouchupinside method

- (void)textDidChangechange{
    
    [self updateTextFieldFrame];
    
    if (self.textField.hasText) {
        
        self.addButton.hidden = NO;
        self.addButton.y = CGRectGetMaxY(self.textField.frame) + 5;
        [self.addButton setTitle:[NSString stringWithFormat:@"添加标签：%@",self.textField.text] forState:UIControlStateNormal];
        
        NSString *text = self.textField.text;
        NSUInteger len = text.length;
        NSString *lastLetter = [text substringFromIndex:len - 1];
        if ([lastLetter isEqualToString:@","] || [lastLetter isEqualToString:@"，"]) {
            self.textField.text = [text substringToIndex:len - 1];
            
            [self addButtonClick];
        }
        
    } else {
        
        self.addButton.hidden = YES;
    }
    
    
    
}


- (void)addButtonClick{
    
    if (self.tagButtons.count == 5) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.contentView animated:YES];
       
        hud.label.text = @"最多添加5个标签";
        [hud hideAnimated:YES afterDelay:3];
        return;
        
    }
    
    TagButton *tagButton = [TagButton buttonWithType:UIButtonTypeCustom];
    [tagButton addTarget:self action:@selector(tagButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [tagButton setTitle:self.textField.text forState:UIControlStateNormal];
    
    [self.contentView addSubview:tagButton];
    [self.tagButtons addObject:tagButton];
    
    self.textField.text = nil;
    self.addButton.hidden = YES;
    
    [self updateTagButtonFrame];
    [self updateTextFieldFrame];
}



#pragma mark private method

- (void)setupNavigation{
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    self.navigationController.title = @"添加标签";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(doneFinished)];
}

- (BOOL)textFieldShouldReturn:(TagTextField *)textField{
    
    if (textField.hasText) {
        [self addButtonClick];
    }
    
    return YES;
}

- (void)doneFinished{
    
    NSArray *tags = [self.tagButtons valueForKeyPath:@"currentTitle"];
    
    !self.tagBlock ? : self.tagBlock(tags);
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.textField endEditing:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
